<?php

class SportManager
{
	private $_db;
	
	public function __construct(PDO $db)
	{
		$this->setDb($db);
	}
	
	public function setDb($db)
	{
		$this->_db = $db;
	}
	
	public function add(Sport $sport)
	{
		//Fonction qui va ajouter un sport dans la table sports
		$reqInsert = $this->_db->prepare("INSERT INTO sports SET name= :name, description= :description");
		$reqInsert->bindValue(":name", $sport->name());
		$reqInsert->bindValue(":description", $sport->description());
		$reqInsert->execute();
		$sport->hydrate(array(
			'id' => $this->_db->lastInsertId()
		));
	}
	public function delete(Sport $sport)
	{
		//Fonction qui va supprimer un sport dans la table sports
		$reqDelete = $this->_db->prepare("DELETE FROM sports WHERE id= :id");
		$reqDelete->bindValue(":id", $sport->id());
		$reqDelete->execute();
	}
	public function update(Sport $sport)
	{
		//Fonction qui va mettre à jour un sport dans la table sports
		$reqUpdate = $this->_db->prepare("UPDATE sports SET name= :name, description= :description WHERE id= :id");
		$reqUpdate->bindValue(":id", $sport->id(), PDO::PARAM_INT);
		$reqUpdate->bindValue(":name", $sport->name(), PDO::PARAM_STR);
		$reqUpdate->bindValue(":description", $sport->description(), PDO::PARAM_STR);
		$reqUpdate->execute();
	}
	public function get($search)
	{
		//Fonction qui va chercher un sport dans la table sports à partir du critère de recherche search
		if(is_int($search))
		{
			$reqSelect = $this->_db->prepare("SELECT * FROM sports WHERE id= :id");
			$reqSelect->bindValue(":id", $search);
			$reqSelect->execute();
			$sport = $reqSelect->fetch(PDO::FETCH_ASSOC);
			return new Sport($sport);
		}
		if(is_string($search))
		{
			$reqSelect = $this->_db->prepare("SELECT * FROM sports WHERE name LIKE :name");
			$reqSelect->bindValue(":name", $search);
			$reqSelect->execute();
			$sport = $reqSelect->fetch(PDO::FETCH_ASSOC);
			return new Sport($sport);
		}
	}
	public function listSports()
	{
		//Fonction qui va restituer la liste des sports
		$reqSelect = $this->_db->prepare("SELECT * FROM sports");
		$reqSelect->execute();
		$sports = array();
		while($sport = $reqSelect->fetch(PDO::FETCH_ASSOC))
		{
			$sportL = new Sport($sport);
			$sports[] = $sportL;
		}
		return $sports;
	}
}